package cn.tradewin.advisor.pages.workflow;

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.List;

import org.apache.shiro.subject.Subject;
import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.beaneditor.BeanModel;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.BeanModelSource;
import org.slf4j.Logger;
import org.tynamo.security.services.SecurityService;

import cn.tradewin.advisor.activiti.service.ActivitiProcessStatus;
import cn.tradewin.advisor.activiti.service.ActivitiService;
import cn.tradewin.advisor.exceptions.DBException;
import cn.tradewin.advisor.persist.model.Vacation;
import cn.tradewin.advisor.persist.services.VacationService;

public class VacationBoard {

	@Inject
	private Messages messages;
	
	@Inject
	private ActivitiService activitiService;
	
	@Inject
	private SecurityService securityService;
	
	@Inject
	private BeanModelSource beanModelSource;
	
	@Property
	private BeanModel<Vacation> beanModel;
	
	@Property
	private List<Vacation> vacations;
	
	@Property
	private Vacation vacation;
	
	@Inject
	private VacationService vacationService;
	
	@Inject
	private Logger log;
	
	@SetupRender
	void setupRender() throws DBException {
		beanModel = beanModelSource.createDisplayModel(Vacation.class, messages);
		beanModel.add("action", null);
		beanModel.include("id", "accountId", "category","motivation", "applyDate","vacationDate", "start", "end", "status", "action");
	}
	
	@OnEvent(EventConstants.PREPARE_FOR_RENDER)
	void prepareForRender() throws Exception {
		Subject subject = securityService.getSubject();
		String userid = (String)subject.getPrincipal();
		vacations = vacationService.listSelfVacations(userid);
		for (Vacation vacation : vacations) {
			if (vacation.getStatus() != -1 && vacation.getProcessId() != null) {
				if (activitiService.getProcessStatus(vacation.getProcessId()).equals(ActivitiProcessStatus.SUSPENDED)) {
					vacation.setStatus(1);
				} else if (activitiService.getProcessStatus(vacation.getProcessId()).equals(ActivitiProcessStatus.ENDED)) {
					vacation.setStatus(-1);
				} else {
					String name = activitiService.getCurrentActivitiName(vacation.getProcessId());
					log.debug("current activiti name is = " + name);
				}
			}
		}
	}
		
	public boolean isEmpty() {
		if (vacations == null || vacations.size() == 0)
			return true;
		return false;
	}
	
	public Format getDateFormat() {
        final Format f = new SimpleDateFormat("yyyy-MM-dd");
        return f;
    }
	
	public Format getTimeFormat() {
		return new SimpleDateFormat("HH:mm");
	}
}